﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Exhibition.Dao.ViewModel;
using AutoMapper;
namespace Exhibition.Dao
{

    public class AreaDao
    {


        public AreaDao()
        {

            Mapper.CreateMap<E_Area, AreaModel>();
        }
        public List<E_Area> GetList(int startIndex, int maxRow, out int recordcount)
        {


            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                recordcount = edm.E_Area.Count();

                return edm.E_Area.OrderByDescending(s => s.Id).Skip(startIndex).Take(maxRow).ToList();

            }

        }


        public AreaModel GetOneById(int id)
        {


            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                var query = edm.E_Area.FirstOrDefault(s => s.Id == id);
                return Mapper.Map<E_Area, AreaModel>(query);
            }

        }


        public int Save(AreaModel obj)
        {


            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                var query = edm.E_Area.FirstOrDefault(s => s.Id == obj.Id);

                if (query == null)
                {


                    query = new E_Area();

                    edm.AddToE_Area(query);

                }


                query.AreaName = obj.AreaName;

                query.AreaCode = obj.AreaCode;

                query.ParentId = obj.ParentId;
                query.CreateUserId = obj.CreateUserId;
                edm.SaveChanges();

                return query.Id;


            }

        }
        /// <summary>
        /// 获取区域
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public List<AreaModel> GetListByPid(int pid)
        {
            using (ExhibitionEntities edm = new ExhibitionEntities())
            {
                var query = edm.E_Area.Where(s => s.ParentId == pid);
                return Mapper.Map<List<E_Area>, List<AreaModel>>(query.ToList());
            }
        }

        /// <summary>
        /// 获取所有区域
        /// </summary>
        /// <returns></returns>
        public List<AreaModel> GetAllArea()
        {
            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                return Mapper.Map<List<E_Area>, List<AreaModel>>(edm.E_Area.ToList());
            }
        }


        public int DelById(int id)
        {


            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                var query = edm.E_Area.FirstOrDefault(s => s.Id == id);

                if (query != null)
                { 
                    edm.DeleteObject(query); 
                } 
                return edm.SaveChanges();  
            }

        }


    }

}

